package com.flipdf2;

import java.util.LinkedList;
import java.util.List;

public class StampList {
	public static final Stamp.TYPE[] sortedType = new Stamp.TYPE[] { Stamp.TYPE.pdf,
			Stamp.TYPE.image, Stamp.TYPE.text };
	private List<Stamp> stampList;

	public StampList() {
		this.stampList = new LinkedList<Stamp>();
	}

	public int size() {
		return this.stampList.size();
	}

	public Stamp getStamp(int index) {
		return stampList.get(index);
	}

	public boolean removeStamp(Stamp stamp) {
		return stampList.remove(stamp);
	}

	public void add(Stamp newStamp) {
		if (this.stampList.contains(newStamp)) {
			return;
		}
		boolean inserted = false;
		for (int i = 0; i < stampList.size(); i++) {
			Stamp stamp = stampList.get(i);
			int res = compare(stamp, newStamp);
			if (res == -1) {
				stampList.add(i, newStamp);
				inserted = true;
			}
		}
		if (!inserted) {
			stampList.add(newStamp);
		}
	}

	private int compare(Stamp stamp1, Stamp stamp2) {
		if (stamp1.getLayer() < stamp2.getLayer()) {
			return -1;
		}

		if (stamp1.getLayer() > stamp2.getLayer()) {
			return 1;
		}

		if (stamp1.getLayer() == stamp2.getLayer()) {
			int type1 = -1;
			int type2 = -1;

			for (int i = 0; i < sortedType.length; i++) {
				if (stamp1.getType() == sortedType[i]) {
					type1 = i;
				}
				if (stamp2.getType() == sortedType[i]) {
					type2 = i;
				}
			}
			if (type1 == type2) {
				return 0;
			}
			return type1 < type2 ? -1 : 1;
		}

		return 0;
	}
}
